<template>
  <div class="login-container">
    <el-card class="login-card">
      <template #header>
        <div class="card-header">
          <h2>{{ isRegister ? '用户注册' : '用户登录' }}</h2>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="80px"
        @submit.prevent
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" />
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
            v-model="form.password"
            type="password"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>

        <template v-if="isRegister">
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input
              v-model="form.confirmPassword"
              type="password"
              placeholder="请再次输入密码"
              show-password
            />
          </el-form-item>

          <el-form-item label="手机号码" prop="phone">
            <el-input v-model="form.phone" placeholder="请输入手机号码" />
          </el-form-item>

          <el-form-item label="电子邮箱" prop="email">
            <el-input v-model="form.email" placeholder="请输入电子邮箱" />
          </el-form-item>
        </template>

        <el-form-item>
          <el-button type="primary" @click="handleSubmit" style="width: 100%">
            {{ isRegister ? '注册' : '登录' }}
          </el-button>
        </el-form-item>

        <div class="form-footer">
          <el-button link @click="toggleMode">
            {{ isRegister ? '已有账号？去登录' : '没有账号？去注册' }}
          </el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { useCustomerStore } from '@/stores/customerStore'

const router = useRouter()
const userStore = useUserStore()
const customerStore = useCustomerStore()
const formRef = ref(null)
const isRegister = ref(false)

const form = ref({
  username: '',
  password: '',
  confirmPassword: '',
  phone: '',
  email: ''
})

const validatePass = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else {
    if (form.value.confirmPassword !== '') {
      formRef.value?.validateField('confirmPassword')
    }
    callback()
  }
}

const validatePass2 = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== form.value.password) {
    callback(new Error('两次输入密码不一致!'))
  } else {
    callback()
  }
}

const rules = computed(() => ({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, validator: validatePass, trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  ...(isRegister.value ? {
    confirmPassword: [
      { required: true, validator: validatePass2, trigger: 'blur' }
    ],
    phone: [
      { required: true, message: '请输入手机号码', trigger: 'blur' },
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
    ],
    email: [
      { required: true, message: '请输入电子邮箱', trigger: 'blur' },
      { type: 'email', message: '请输入正确的电子邮箱地址', trigger: 'blur' }
    ]
  } : {})
}))

const toggleMode = () => {
  isRegister.value = !isRegister.value
  form.value = {
    username: '',
    password: '',
    confirmPassword: '',
    phone: '',
    email: ''
  }
  formRef.value?.clearValidate()
}

const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    
    if (isRegister.value) {
      // 注册新用户
      const { confirmPassword, ...registerData } = form.value
      await customerStore.register(registerData)
      ElMessage.success('注册成功，请登录')
      isRegister.value = false
      form.value = {
        username: registerData.username,
        password: '',
        confirmPassword: '',
        phone: '',
        email: ''
      }
    } else {
      // 尝试登录
      try {
        // 模拟登录处理
        if (form.value.username === 'purchaser' && form.value.password === 'purchaser123') {
          // 模拟成功登录响应
          const mockResponse = {
            user: {
              id: 1,
              username: 'purchaser',
              role: 'purchaser',
              email: 'purchaser@example.com'
            },
            access: 'mock-token',
            refresh: 'mock-refresh-token'
          }
          
          // 保存用户信息和token
          userStore.setToken(mockResponse.access)
          userStore.setUser(mockResponse.user)
          
          // 跳转到采购员仪表盘
          router.push('/purchaser/dashboard')
          ElMessage.success('登录成功')
          return
        }
        
        // 如果不是测试账号，尝试正常登录流程
        const response = await userStore.login({
          username: form.value.username,
          password: form.value.password
        })
        
        // 根据用户角色跳转到不同的页面
        const rolePathMap = {
          customer: '/customer/products',
          salesman: '/salesman/dashboard',
          deliveryman: '/deliveryman/dashboard',
          admin: '/admin/dashboard',
          purchaser: '/purchaser/dashboard'  // 添加采购员角色路由
        }
        router.push(rolePathMap[response.user.role.toLowerCase()] || '/login')
      } catch (error) {
        // 如果系统用户登录失败，尝试作为客户登录
        try {
          const customer = await customerStore.login(
            form.value.username,
            form.value.password
          )
          router.push('/customer/products')
        } catch (customerError) {
          ElMessage.error('用户名或密码错误')
        }
      }
    }
  } catch (error) {
    ElMessage.error(error.message || '表单验证失败')
  }
}
</script>

<style scoped>
.login-container {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f0f2f5;
}

.login-card {
  width: 400px;
}

.card-header {
  text-align: center;
}

.card-header h2 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.form-footer {
  text-align: center;
  margin-top: 20px;
}
</style>